import React from 'react';

const genValidConfig = (name: string) => {
  const config = [
    { required: true, message: `${name} is required` },
  ];

  return config;
};

// 获取父节点 id
const getParentKey = (key: any, tree: any): any => {
  let parentKey;
  for (let i = 0; i < tree.length; i += 1) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item: any) => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }

  return parentKey;
};

// 获取待展开的元素
const getExpandedKeys = (value: number | string, tree: Array<any>, dictList: Array<any>) => dictList
  .map((item: any) => {
    if (item.text.indexOf(value) > -1) {
      return getParentKey(item.id, tree);
    }
    return null;
  })
  .filter((item: any, i: number, self: any) => item && self.indexOf(item) === i);

// 生成搜索字典
const generateList = (data: any, dictList: Array<any>) => {
  for (let i = 0; i < data.length; i += 1) {
    const node = data[i];
    const { id, text } = node;
    dictList.push({ id, text });
    if (node.children) {
      generateList(node.children, dictList);
    }
  }
};

// 搜索树
const loop = (data: any, search: string) => data.map((item: any) => {
  const index: number = item.text.indexOf(search);
  const beforeStr = item.text.substr(0, index);
  const afterStr = item.text.substr(index + search.length);

  const node = index > -1 ? (
    <span>
      {beforeStr}
      <span className="text-red-500 font-bold">{search}</span>
      {afterStr}
    </span>
  ) : (
    <span>{item.text}</span>
  );

  if (item.children) {
    return { title: node, key: item.id, children: loop(item.children, search) };
  }

  return {
    title: node,
    key: item.id,
  };
});

// 点击文本时 获取子节点 id list；用于模拟全选功能
const getAllChildList = (key: string | undefined, tree: Array<any>): Array<string> => {
  let curkey = key;

  if (!key) {
    curkey = tree[0].key;
  }

  const result = [curkey] as Array<string>;

  const deep = (data: Array<any>) => {
    for (let i = 0, len = data.length; i < len; i += 1) {
      const v = data[i];
      result.push(v.key);
      if (v.children && v.children.length) {
        deep(v.children);
      }
    }
  };

  const find = (data: Array<any>) => {
    for (let i = 0, len = data.length; i < len; i += 1) {
      const v = data[i];
      if (v.key === curkey) {
        deep(v.children || []);
        break;
      } else if (v.children && v.children.length) {
        find(v.children);
      }
    }
  };

  find(tree);
  return result;
};

export { genValidConfig, getExpandedKeys, generateList, loop, getAllChildList };
